<script setup lang="ts">
import {computed, ref} from "vue";
import {useAuthStore} from "@/store/modules/auth";
import {NCard, NForm, NFormItem, NInput, NTabPane, NTabs, UploadFileInfo} from "naive-ui";
import {localStg} from '@/utils/storage';
import {createProxyPattern, createServiceConfig} from "~/env.config";
import {fetchUpdateUserInfo} from "@/service/api";
import {REG_EMAIL} from "@/constants/reg";

const authStore = useAuthStore();
const userInfo = ref<Api.Entity.User>({
  email: authStore.userInfo.email,
  nickName: authStore.userInfo.nickName,
  avatar: authStore.userInfo.avatar,
  phoneNumber: authStore.userInfo.phoneNumber,
  id: authStore.userInfo.id,
  enabled: authStore.userInfo.enabled,
});
const rules = ref<any>({
  email: {
    pattern: REG_EMAIL,
    required: true,
    message: '请输入邮箱地址',
    trigger: ['input', 'blur']
  },
  nickName: {
    required: true,
    message: '请输入姓名',
    trigger: ['input', 'blur']
  },
  phoneNumber: {
    required: true,
    message: '请输入电话号码',
    trigger: ['input', 'blur'],
  },
});
const formRef = ref();
const {baseURL} = createServiceConfig(import.meta.env);
const isHttpProxy = import.meta.env.VITE_HTTP_PROXY === 'Y';
const uploadAction = computed(() => {
  let baseUrl = isHttpProxy ? createProxyPattern() : baseURL;
  return baseUrl + '/current/upload-avatar'
})
const headers = ref({})
headers.value['Authorization'] = 'Bearer ' + localStg.get('token');
const uploadFinish = (file: UploadFileInfo) => {
  let res = (file.event.target as XMLHttpRequest).response
  //json字符串转json对象
  let resObj = JSON.parse(res);
  if (resObj.code === 'success') {
    userInfo.value.avatar = resObj.data
  } else {
    window.$message?.error(resObj.msg)
  }
}
const save = () => {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      let {error} = await fetchUpdateUserInfo(userInfo.value);
      if (!error) {
        await authStore.updateUserInfo()
        window.$message?.success('保存成功')
      } else {
        window.$message?.error(error.message)
      }
    }
  })
}
</script>
<template>
  <div class="flex-vertical-stretch gap-16px overflow-hidden <sm:overflow-auto">
    <NCard title="" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden"
           content-style="padding: .5rem !important;">
      <n-tabs type="bar" animated placement="left" :style="{ }">
        <n-tab-pane name="oasis" tab="个人资料">
          <n-form
            ref="formRef"
            :model="userInfo"
            :rules="rules"
            label-placement="left"
            :label-width="180"
            require-mark-placement="right-hanging"
            size="medium"
            :style="{maxWidth: '640px' }"
          >
            <n-form-item label="头像：" path="avatar" required require-mark-placement="left">
              <n-upload :action="uploadAction"
                        :headers="headers"
                        accept="image/*"
                        :max="1"
                        @finish="uploadFinish"
                        :multiple="false"
                        :default-file-list="[
                  {
                    url: userInfo.avatar || '',
                    id: '1',
                    name: 'avatar.png',
                    status: 'finished'
                  }]"
                        list-type="image-card"
              >
                点击上传
              </n-upload>
            </n-form-item>
            <n-form-item label="邮箱地址：" path="email" required require-mark-placement="left">
              <n-input v-model:value="userInfo.email"/>
            </n-form-item>
            <n-form-item label="姓名：" path="nickName" required require-mark-placement="left">
              <n-input v-model:value="userInfo.nickName"/>
            </n-form-item>
            <n-form-item label="电话号码：" path="phoneNumber" required require-mark-placement="left">
              <n-input v-model:value="userInfo.phoneNumber"/>
            </n-form-item>
            <n-form-item>
              <n-space style="width: 100%;display: flex;justify-content: flex-end">
                <n-button type="primary" @click="save">
                  <template #icon>
                    <icon-material-symbols-save/>
                  </template>
                  保存
                </n-button>
              </n-space>
            </n-form-item>
          </n-form>
        </n-tab-pane>
        <n-tab-pane name="profile" tab="登录信息">
          Wonderwall
        </n-tab-pane>

      </n-tabs>
    </NCard>
  </div>
</template>

<style scoped></style>
